package com.fg.cloud.manager.service.agency.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fg.cloud.common.CommonConstants;
import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.construction.Tree;
import com.fg.cloud.common.finals.Agency;
import com.fg.cloud.manager.entry.BaseEntity;
import com.fg.cloud.manager.entry.agency.AgencyProductEntity;
import com.fg.cloud.manager.entry.agency.vo.AgencyProductVo;
import com.fg.cloud.manager.mapper.BaseMapper;
import com.fg.cloud.manager.mapper.agency.AgencyProductMapper;
import com.fg.cloud.manager.service.BaseServiceImpl;
import com.fg.cloud.manager.service.agency.AgencyProductService;
import com.google.common.collect.Lists;

/**
 * 经销商-订货权限service实现
 * @author around
 * @date 2017-6-26
 */
@Service
public class AgencyProductServiceImpl extends BaseServiceImpl implements AgencyProductService {

	@Autowired
	private AgencyProductMapper agencyProductMapper;
	
	@Override
	protected <T extends BaseEntity> BaseMapper getBaseMapper() {
		return agencyProductMapper;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public AgencyProductEntity find(long id) {
		return agencyProductMapper.selectByPrimaryKey(id);
	}

	/**
	 * 经销商订货权限模块列表查询
	 */
	@Override
	public List<Tree> findList(Long facId, Long ageId) {
		tableIsExit(facId);
		List<Tree> treeList = agencyProductMapper.selectAgencyCategorys(Agency.getTableName(facId),
				facId, ageId);
		
		Map<Long, List<Tree>> map = new HashMap<Long, List<Tree>>();
		List<Tree> tempList = null;
		Tree tree = null;
		
		for (int i = 0; i < treeList.size(); i++) {
			tree = treeList.get(i);
			//判断是否已有同级内容
			if(null == map.get(tree.getPid())) tempList = Lists.newArrayList();
			else tempList = map.get(tree.getPid());
			//根据当前节点查找下级节点集合是否存在，有则纳入封装体系
			if(map.get(tree.getId()) != null)
				tree.setChildren(map.get(tree.getId()));
			tempList.add(tree);
			map.put(tree.getPid(), tempList);
		}
		return map.get(0L);
	}
	
	@Override
	public List<Tree> findAddAgencyProductByCategorys(Long facId, Long ageId) {
		List<Tree> treeList = agencyProductMapper.selectAddAgencyProductByCategorys(
				Agency.getTableName(facId), facId, ageId);
		
		Map<Long, List<Tree>> map = new HashMap<Long, List<Tree>>();
		List<Tree> tempList = null;
		Tree tree = null;
		
		for (int i = 0; i < treeList.size(); i++) {
			tree = treeList.get(i);
			tree.setChecked(tree.getType() > 0 ? true : false);//设置是否选中
			//判断是否已有同级内容
			if(null == map.get(tree.getPid())) tempList = Lists.newArrayList();
			else tempList = map.get(tree.getPid());
			//根据当前节点查找下级节点集合是否存在，有则纳入封装体系
			if(map.get(tree.getId()) != null)
				tree.setChildren(map.get(tree.getId()));
			
			tempList.add(tree);
			map.put(tree.getPid(), tempList);
		}
		return map.get(0L);
	}
	
	@Override
	@Transactional
	public boolean refreshAgencyProductByCategory(Long facId, Long ageId, 
			String originalIds, String categoryIds) {
		boolean flag = true;
		flag = batchDeletes(facId, ageId, null);
		//判断清空订货权限
		if(null != categoryIds && categoryIds.length() > 0)
			flag = batchInserts(facId, ageId, categoryIds.split("[, ]+"));
		/*List<Long> removeList = Lists.newArrayList();
		List<String> addList = Lists.newArrayList();
		String[] oldIdArray = originalIds.split("[, ]+");
		String[] newIdArray = categoryIds.split("[, ]+");
		//处理动态删除和新增数据
		for (int i = 0; i < oldIdArray.length; i++) {
			if (!categoryIds.contains(oldIdArray[i]))
				removeList.add(Long.valueOf(oldIdArray[i]));
		}
		for (int i = 0; i < newIdArray.length; i++) {
			if (!originalIds.contains(newIdArray[i]))
				addList.add(newIdArray[i]);
		}
		//删除旧数据
		if (removeList.size() > 0) {
			flag = batchDeletes(facId, ageId, removeList.toArray(new Long[removeList.size()]));
		}
		//添加新数据
		if (addList.size() > 0) {
			flag = batchInserts(facId, ageId, addList.toArray(new String[addList.size()]));
		}*/
		return flag;
	}
	
	/**
	 * 检查表是否存在，如果不存在则创建，用于新增、保存、删除检查
	 * @param facId 厂商ID
	 * @return true 成功
	 */
	@Override
	@Transactional
	public boolean tableIsExit(Long facId) {
		int count = agencyProductMapper.selectTableExist(CommonConstants.DATABASE, 
				Agency.getTableName(facId));
		if(count == 0) {
			count = agencyProductMapper.createTable(Agency.getTableName(facId));
		}
		return count > 0 ? true : false;
	}


	@Override
	@Transactional
	public boolean batchDeletes(Long facId, Long ageId, Long[] ids) {
		return agencyProductMapper.batchDeletesByCategorys(Agency.getTableName(facId), 
				facId, ageId, ids) > 0 ? true : false;
	}

	@Override
	@Transactional
	public boolean batchInserts(Long facId, Long ageId, String[] categoryIds) {
		return agencyProductMapper.batchInsertsByCategorys(Agency.getTableName(facId), 
				facId, ageId, 0, categoryIds) > 0 ? true : false;
	}
	
	public static void main(String[] args) {
		AgencyProductServiceImpl test = new AgencyProductServiceImpl();
		test.refreshAgencyProductByCategory(0L, 0L, "1,5,6,8,4","5,8,6,7");
	}

	@Override
	public void selectAgencyProductByCategorys(PageUtils<AgencyProductVo> pageinfo) {
		agencyProductMapper.selectAgencyProductByCategorys(pageinfo);
	}

}
